/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type Params = {
  face: string;
  tools: string[];
};

function CmdSplitFace({ title, onClose, props }: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState({
    face: null,
    tools: [null],
  });
  const schema: RJSFSchema = {
    properties: {
      face: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
        uniqueItems: true,
      },
      tools: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickALL,
        uniqueItems: true,
      },
    },
  };

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({ face: null, tools: [null] });
      return;
    }

    const params: Params = props.params;
    const { face, tools } = params;

    await initEditDependency([face, ...tools]);

    setFormData({
      face: picker.generatePickObjByPickID(face) as pickedFaceData,
      tools: tools.map((tool) => picker.generatePickObjByPickID(tool)),
    });
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-split-face', {
      commandName: 'CreateSplitFace',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    return confirmCommand(
      {
        a: {
          face: formData.face.meshId,
          tools: formData.tools.map((c) => c.idInfo.o),
        },
      },
      preview,
    );
  };

  const isFormDataValid = () => {
    return (
      formData.face &&
      formData.tools.length >= 1 &&
      formData.tools.every((c) => c != null)
    );
  };

  const preview = async () => {
    clear();

    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  useEffect(() => {
    clear();
  }, [formData.face, formData.tools]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        face: {
          'ui:placeholder': '请输入被分割的面',
          'ui:autofocus': true,
        },
        tools: {
          'ui:placeholder': '请输入用于分割的工具',
        },
      }}
      formData={formData}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdSplitFace: CurvedBaseCommand = {
  id: 'CmdSplitFace',
  label: 'command.split-face',
  icon: 'commands/feature/split-face',
  create: (label, onClose, props) => (
    <CmdSplitFace
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
